package com.tripshare.sdk.weixin.api.gateway;

import com.google.gson.Gson;
import com.tripshare.sdk.weixin.api.*;
import com.tripshare.sdk.weixin.converter.Converter;
import com.tripshare.sdk.weixin.converter.ConverterFactory;
import com.tripshare.sdk.weixin.api.util.AccessTokenUtil;
import com.tripshare.sdk.weixin.api.util.CryptUtil;
import com.tripshare.sdk.weixin.format.WeixinBaseMsg;
import com.tripshare.sdk.weixin.format.WeixinBaseReplyMsg;
import com.tripshare.sdk.weixin.format.receive.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Slf4j
@CrossOrigin
@RequestMapping("/api")
@RestController
public class GatewayController {

    @Autowired
    private WeixinConfig weixinConfig;

    @Autowired
    private IMsgProcessor msgProcessor;

    private static final Gson gson = new Gson();

    private static RestTemplate restTemplate = new RestTemplate();

    /**
     * 接收微信通知
     *
     * @param body
     * @return
     */
    @RequestMapping("/weixin/gateway")
    public String receiveWeixinMsg(@RequestParam(value = "timestamp", required = false) String timestamp,
                                   @RequestParam(value = "nonce", required = false) String nonce,
                                   @RequestParam(value = "encrypt_type", required = false) String encrypt_type,
                                   @RequestParam(value = "msg_signature", required = false) String msg_signature,
                                   @RequestParam(value = "signature", required = false) String signature,
                                   @RequestParam(value = "echostr", required = false) String echostr,
                                   @RequestBody(required = false) String body) throws Exception {

        log.info("receiveWeixinMsg timestamp={} nonce={} encrypt_type={} msg_signature={} signature={} echostr={} body={}", timestamp, nonce, encrypt_type, msg_signature, signature, echostr, body);

        if (StringUtils.isNotBlank(echostr)) {
            //验证token，开发者配置才能生效
            return echostr;
        }

        //密文才需要准备这个参数
        WeixinParameter weixinParameter = new WeixinParameter();
        weixinParameter.setEncodingAesKey(weixinConfig.getEncodingAesKey());
        weixinParameter.setToken(weixinConfig.getToken());
        weixinParameter.setAppId(weixinConfig.getAppId());
        weixinParameter.setTimestamp(timestamp);
        weixinParameter.setNonce(nonce);
        weixinParameter.setMsgSignature(msg_signature);
        weixinParameter.setContent(body);

        String decryptedMsg;
        if (StringUtils.isBlank(encrypt_type)) {
            //明文格式
            decryptedMsg = body;
        } else {
            //密文格式，解密消息
            decryptedMsg = CryptUtil.decryptMsg(weixinParameter);
        }

        log.info("decryptedMsg={}", decryptedMsg);

        //获取相应消息的反序列化器
        Converter receiveConverter = ConverterFactory.getReceiveConverter(decryptedMsg);
        if (receiveConverter == null) {
            log.info("没有找到与接收消息对应的converter");
            //默认不处理
            return "success";
        }

        WeixinBaseMsg receiveMsg = receiveConverter.convert(decryptedMsg);

        //消息类型分发处理
        WeixinBaseReplyMsg replyMsg = dispatch(receiveMsg);

        //回复消息
        if (replyMsg != null) {
            Converter replyConverter = ConverterFactory.getReplyConverter(replyMsg);
            String replyXmlMsg = replyConverter.convert(replyMsg);

            log.info("明文回复消息 replyXml={}", replyXmlMsg);
            if (StringUtils.isBlank(encrypt_type)) {
                return new String(replyXmlMsg.getBytes("utf-8"), "ISO-8859-1");
            } else {
                weixinParameter.setContent(replyXmlMsg);
                //加密消息
                String encryptMsg = CryptUtil.encryptMsg(weixinParameter);
                log.info("密文回复消息encryptMsg={}", encryptMsg);
                return encryptMsg;
            }
        } else {
            //默认不处理
            return "success";
        }

    }

    private WeixinBaseReplyMsg dispatch(WeixinBaseMsg receiveMsg) throws InvocationTargetException, IllegalAccessException {
        //根据消息类型匹配  -> 合适的处理器
        Method[] declaredMethods = IMsgProcessor.class.getDeclaredMethods();
        for (int i = 0; i < declaredMethods.length; i++) {
            Method declaredMethod = declaredMethods[i];

            Class<?>[] parameterTypes = declaredMethod.getParameterTypes();
            if (parameterTypes.length == 1 && parameterTypes[0] == receiveMsg.getClass()) {
                WeixinBaseReplyMsg replyMsg = (WeixinBaseReplyMsg) declaredMethod.invoke(msgProcessor, receiveMsg);
                return replyMsg;
            }
        }

        log.info("不支持的消息类型，请检查代码");
        return null;
    }

    /**
     * 应用程序为公众号创建自定义菜单
     *
     * @param menuFilePath 菜单在linux服务器上的位置
     * @return
     */
    @RequestMapping("/weixin/menu/create")
    public String createMenu(@RequestParam(value = "menuFilePath", required = false) String menuFilePath) throws IOException {
        log.info("menuFilePath={}", menuFilePath);
        FileSystemResource fileSystemResource = new FileSystemResource(menuFilePath);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try (InputStream inputStream = fileSystemResource.getInputStream()) {
            IOUtils.copy(inputStream, bos);
            String menuJson = bos.toString("ISO-8859-1");
            log.info("menuJson={}", menuJson);
            HttpEntity request = new HttpEntity(menuJson);
            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity("https://api.weixin.qq.com/cgi-bin/menu/create?access_token={access_token}", request, String.class, AccessTokenUtil.getAccessToken());
            log.info("createMenu result={}", stringResponseEntity.getBody());
            return "success";
        }
    }

}
